<!--搜索表单 泰尔茂项目发起-新搜索表单20210409-->
<template>
  <div class="gkSearchForm">
    <el-form
      :inline="true"
      :model="formInline"
      :label-position="labelPosition"
      class="el-form--inline filter-box"
    >
      <el-form-item
        v-for="item in searchData"
        :key="item.index"
        class="m-form-item"
        :class="{ badge: item.type === 'badge' }"
      >
        <!-- 输入框 -->
        <div v-if="item.type === 'input'">
          <el-input
            class="inputText"
            v-model="formInline[item.key]"
            v-bind="item.attr"
            :placeholder="item.title"
          />
        </div>
        <!-- 远程搜索 -->
        <div v-if="item.type === 'autocomplete'">
          <el-autocomplete
            v-model="formInline[item.key]"
            v-bind="item.attr"
            @select="handleSelect"
          />
        </div>
        <!-- 下拉选择 -->
        <div v-if="item.type === 'select'">
          <el-select
            :style="{ width: calcWidth(item) }"
            v-model="formInline[item.key]"
            v-bind="item.attr"
            :placeholder="item.title"
            @focus="focuskey(item.key)"
            @change="selectChange($event)"
          >
            <el-option
              v-for="items in item.options"
              :title="items.label"
              :key="items.value"
              :label="items.label"
              :value="items.value"
            />
          </el-select>
        </div>
        <!-- 日期 -->
        <div v-if="item.type === 'time'">
          <el-date-picker
            v-model="formInline[item.key]"
            v-bind="item.attr"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </div>
        <!-- 单独日期 -->
        <div class="dateTime" v-if="item.type === 'date'">
          <el-date-picker
            v-model="formInline[item.key]"
            v-bind="item.attr"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </div>
        <!-- 日期区间 -->
        <div class="timedaterange" v-else-if="item.type == 'timedaterange'">
          <el-date-picker
            v-model="formInline[item.key[0]]"
            v-bind="item.attr[0]"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
          <span class="time_line">-</span>
          <el-date-picker
            v-model="formInline[item.key[1]]"
            v-bind="item.attr[1]"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </div>
        <!-- 单选 -->
        <div v-if="item.type === 'radio'">
          <template>
            <el-radio
              class="m-radio"
              v-for="items in item.options"
              :key="items.value"
              v-model="formInline[item.key]"
              :label="items.value"
              v-bind="item.attr"
              >{{ items.label }}</el-radio
            >
          </template>
        </div>
        <!-- 标记 -->
        <div v-if="item.type === 'badge'">
          <template>
            <el-badge
              v-for="(items, i) in item.options"
              :key="i"
              class="m-badge"
              :class="{ 'badge-active': badgeKey === items.value }"
            >
              <el-button
                class="badge-button"
                @click="changeStatus(item.key, items.value)"
                size="small"
              >
                {{ items.label }}
              </el-button>
            </el-badge>
          </template>
        </div>
        <!-- 级联 -->
        <div v-if="item.type === 'cascader'">
          <el-cascader
            v-model="formInline[item.key]"
            :options="item.options"
            v-bind="item.attr"
            :props="item.optionProps"
          />
        </div>
      </el-form-item>
      <!-- 操作按钮 -->
      <el-form-item class="searchButtonList m-form-item">
        <el-button class="submit" type="primary" @click.stop="search">
          <m-iconfont
            classify="taiermao"
            color="#fff"
            size="14"
            icon="iconchaxun1x"
          />
          <span>查询</span>
        </el-button>
        <el-button class="reset" plain @click.stop="reset">
          <m-iconfont
            classify="taiermao"
            color="#666"
            size="14"
            icon="iconzhongzhi1x"
          />
          <span>重置</span>
        </el-button>
        <el-button
          class="more"
          type="text"
          v-if="showCollapse && more"
          @click="showCollapseData"
        >
          <span v-if="collapse">
            <m-iconfont
              classify="taiermao"
              color="#666"
              size="14"
              icon="iconxialagengduo1x"
            />
          </span>
          <span v-else class="rotate180">
            <m-iconfont
              classify="taiermao"
              color="#666"
              size="14"
              icon="iconxialagengduo1x"
            />
          </span>
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { formatDate } from '@const/filter';
import { isObject, cloneDeep, debounce } from 'lodash';
export default {
  name: 'Search',
  props: {
    data: {
      type: Array,
      default: () => [],
    },
    // 自定义label-width长度
    labelWidth: {
      type: String,
      default: () => '',
    },
    // 第几个表单
    index: {
      type: String,
      default: () => '',
    },
    labelPosition: {
      type: String,
      default: 'right',
    },
  },
  data() {
    // 获取字段，设置默认为空
    let item = this.data;
    let formInlineBox = {};
    // 用于badge 默认值
    let badgeKey = null;
    item.forEach((item) => {
      // 如果有默认值
      if (item.value) {
        formInlineBox[item.key] = item.value;
        // 用于tab默认值
        if (item.type === 'badge') {
          badgeKey = item.value;
        }
      } else {
        if (item.type === 'badge') {
          badgeKey = '';
        } else if (item.type === 'cascader') {
          formInlineBox[item.key] = [];
        } else {
          formInlineBox[item.key] = null;
        }
      }
    });
    return {
      // 内容数据
      formInline: {
        ...formInlineBox,
      },
      // 用于badge
      badgeKey,
      collapse: true,
      showCollapse: false,
      lineNum: 0,
      searchData: cloneDeep(this.data),
      more: true,
    };
  },
  watch: {
    data: {
      handler(nv) {
        this.searchData = cloneDeep(nv);
      },
      deep: true,
    },
  },
  created() {
    // 去抖动
    this.resetSearchDataDebounce = debounce(this.resetSearchData, 100);
  },
  mounted() {
    if (document.getElementsByClassName('gkSearchForm')[0] !== undefined) {
      this.showData();
      window.addEventListener('resize', () => {
        this.resetSearchDataDebounce();
      });
    }
  },
  methods: {
    // 进入页面后根据屏幕像素确定要展示几个表单
    showData() {
      // 一个页面多个表单时可能会用到
      let index = 0;
      if (this.index) {
        index = this.index;
      }
      let search_w =
        document.getElementsByClassName('gkSearchForm')[index].scrollWidth;
      let btn_w = 210;
      let data =
        document
          .getElementsByClassName('gkSearchForm')
          [index].getElementsByClassName('el-form-item') || [];
      let len = data.length > 0 ? btn_w : 0;
      for (let i = 0; i < data.length; i++) {
        len += data[i].scrollWidth + 10;
        if (len > search_w) {
          this.lineNum = i;
          this.showCollapse = true;
          this.lineNum = this.lineNum < 1 ? 1 : this.lineNum; // 至少展示一个搜索项
          let curSearchData = this.searchData.slice(0, this.lineNum);
          this.searchData = curSearchData;
          if (data.length - 1 > this.lineNum) {
            this.more = true;
          } else {
            this.more = false;
          }
          return false;
        } else {
          this.more = false;
        }
      }
      if (this.showCollapse === true && this.more) {
        this.searchData = this.searchData.slice(0, this.lineNum);
      }
    },
    selectChange(event) {
      console.log(event);
    },
    calcWidth(item) {
      this.p = this.p || window.document.createElement('span');
      this.p.innerHTML = item.title;
      this.p.style.position = 'fixed';
      this.p.style.top = '100%';
      this.p.style.fontSize = '14px';
      window.document.body.appendChild(this.p);
      let pWidth = this.p.offsetWidth;
      pWidth = pWidth > 64 ? pWidth : 64;
      let width = pWidth + 18 + 14 + 20 + 'px';
      return width;
    },
    showCollapseData() {
      this.collapse = !this.collapse;
      if (this.collapse === true) {
        // 收起展示一行数据
        this.showData();
      } else {
        // 展开显示全部数据
        this.searchData = this.data;
      }
    },
    // 随着窗口大小变化展示数据
    resetSearchData() {
      this.searchData = cloneDeep(this.data);
      setTimeout(() => {
        this.showData();
      }, 10);
    },
    // 状态tab切换
    changeStatus(key, value) {
      this.formInline[key] = value;
      this.badgeKey = value || '';
      // 点击tab切换的时候直接查询列表
      // this.search()
    },
    // 用于保存select为搜索下拉时使用
    focuskey(key) {
      this.selectkey = key;
      this.$emit('focuskey', this.selectkey);
    },
    handleSelect(item) {
      console.log('287item', item);
    },
    // 点击搜索
    search() {
      // 表单数据
      let formData = {
        ...this.formInline,
      };
      // 时间处理  为了点击提交不需要转换时间
      // 这里做了一个处理 在外层需要添加fieldname字段
      // fieldname为数组 必须两个值['开始时间字段',结束时间字段]
      this.searchData.forEach((item) => {
        if (item.type === 'timedaterange') {
          // timedaterange类型去掉不需要的key
          let curKey = item.key.join(',');
          if (formData[item.key[1]]) {
            formData[item.key[1]] = formData[item.key[1]].replace(
              '00:00:00',
              '23:59:59'
            );
          }
          delete formData[curKey];
        }
        // 判断当前处理的时间一定是时间段
        if (item.type === 'time' && item.attr.type === 'daterange') {
          // 判断有没有选时间 且有fieldname字段
          if (formData[item.key] && item.fieldname) {
            // 开始时间
            formData[item.fieldname[0]] = formatDate(
              formData[item.key][0],
              'YYYY-MM-DD HH:mm:ss'
            );
            // 结束时间
            formData[item.fieldname[1]] = formatDate(
              formData[item.key][1],
              'YYYY-MM-DD HH:mm:ss'
            );
            // 删除多余的时间数组
            delete formData[item.key];
          }
        }
        // 处理单个时间
        if (item.type === 'time' && item.attr.type === 'date') {
          // 确定选了时间才处理
          if (formData[item.key]) {
            // 时间转换
            // 替换原来字段内容
            formData[item.key] = formatDate(
              formData[item.key],
              'YYYY-MM-DD HH:mm:ss'
            );
          }
        }
        // 对多类目处理-只返回一个ID
        if (item.type === 'cascader') {
          if (formData[item.key]) {
            if (isObject(formData[item.key])) {
              let index = formData[item.key].length;
              if (index > 0) {
                if (item.resultType === 'array') {
                  formData[item.key] = formData[item.key];
                } else {
                  formData[item.key] = formData[item.key][index - 1] + '';
                }
              } else {
                formData[item.key] = null;
              }
            }
          } else {
            formData[item.key] = null;
          }
        }
      });
      this.$emit('searchForm', formData);
    },
    // 点击重置
    reset() {
      let arr = this.searchData;
      let DefaultFormInlineBox = {};
      // 用于badge 默认值
      let badgeKey = null;
      arr.forEach((item) => {
        // 如果有默认值
        if (item.value) {
          DefaultFormInlineBox[item.key] = item.value;
          // 用于tab默认值
          if (item.type === 'badge') {
            badgeKey = item.value;
          }
        } else {
          DefaultFormInlineBox[item.key] = null;
          if (item.type === 'cascader') {
            DefaultFormInlineBox[item.key] = [];
          }
        }
      });
      this.formInline = DefaultFormInlineBox;
      this.$emit('resetForm', this.formInline);
    },
  },
};
</script>

<style lang="less">
.gkSearchForm {
  background: #fff;
  margin-bottom: 10px;

  .filter-box {
    flex: 1;
    margin-top: 20px;

    .m-radio {
      width: 60px !important;
      margin: 10px 0 0 0;
    }

    .m-badge {
      margin-right: 14px;
      line-height: 20px;
    }

    .badge-button {
      border: 0 !important;
      border-radius: 14px;
      margin-top: 4px;
    }

    .badge-active {
      .badge-button {
        background: #4d84ff;
        color: #fff;
      }
    }

    .m-form-item {
      margin-bottom: 10px;
      margin-right: 10px;
    }

    .el-form-item__label {
      padding-right: 10px;
      height: 34px;
      line-height: 34px;
    }
    .el-form-item__content {
      height: 38px;
      div {
        // 处理输入框因inline-block引起的间距问题
        width: auto;
        height: 38px;
        font-size: 0;
      }
      .el-select__caret {
        line-height: 38px; // 处理小箭头的样式
      }
      .el-date-editor {
        .el-range__icon {
          line-height: 26px; // 小箭头的样式
          position: absolute;
          left: 220px;
        }
        .el-range__close-icon {
          position: absolute;
          right: 25px;
        }
        .el-range-separator {
          line-height: 36px; // 小箭头的样式
          padding-right: 20px;
        }
        .el-range-input {
          text-align: left;
        }
      }
      .inputText {
        width: 220px;
      }
      .dateTime {
        .el-input__inner {
          text-indent: 0px;
          width: 140px;
        }
        .el-input__prefix {
          left: 110px;
        }
        .el-input__suffix {
          right: 25px;
        }
      }
      .timedaterange {
        .el-input__inner {
          text-indent: 0px;
          width: 140px;
        }
        .el-input__prefix {
          left: 110px;
        }
        .el-input__suffix {
          right: 25px;
        }
      }
      .el-icon-date {
        // date
        font-size: 14px;
      }
      .el-input__icon::before {
        // date
        font-size: 14px;
      }
      .el-input__inner {
        color: #333;
        height: 38px;
        font-size: 14px;
        border: 1px solid #ccc;
        border-radius: 3px;
        padding: 0 26px 0 10px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .daterange {
        width: 245px;
      }
      .time_line {
        font-size: 14px;
        padding: 0 8px;
        line-height: 32px;
      }
      .el-cascader {
        .el-input {
          .el-icon-arrow-down {
            line-height: 36px;
          }
        }
      }
    }
  }
  // 展开收起/查询/重置
  .searchButtonList {
    margin-right: 8px !important;
    margin-top: -1px;
    .el-button {
      border-radius: 3px;
      height: 38px;
      padding: 0;
      margin: 0 10px 0 -4px;
    }
    .iconfont {
      font-size: 14px;
    }
    .submit {
      padding: 0 10px;
      border: 0;
      .iconchaxun1x:before {
        font-size: 14px;
      }
      > span {
        height: 14px;
        display: flex;
        justify-content: center;
        svg {
          padding-right: 8px;
        }
      }
    }
    .reset {
      padding: 0 10px;
      border: 1px solid #ccc;
      > span {
        height: 14px;
        display: flex;
        justify-content: center;
      }
    }
    .more {
      width: 38px;
      height: 38px;
      border: 1px solid #ccc;
      color: #ccc;
    }
    .rotate180 {
      display: block;
      transform: rotate(180deg);
    }
  }

  .el-range-editor--medium .el-range-separator {
    line-height: 36px;
  }

  .el-range-editor--medium .el-range__icon,
  .el-range-editor--medium .el-range__close-icon {
    line-height: 21px;
  }
}
// 下拉框
.el-select-dropdown__item {
  color: #26344c;
  overflow: unset; // 下拉选项展示完整
  &.selected {
    background: #fafafb;
    span {
      color: #26344c;
      font-weight: normal;
    }
  }
  &.hover {
    background: #f5faff;
  }
}
.el-scrollbar {
  .el-scrollbar__wrap {
    .el-select-dropdown__list {
      padding: 0 0 10px 0;
    }
  }
}
</style>
